<template>
  <div class="xtx-numbox">
    <div class="label" v-if="isCount">数量</div>
    <div class="numbox">
      <a href="javascript:;" @click="desc">-</a>
      <input type="text" readonly :value="count" />
      <a href="javascript:;" @click="ins">+</a>
    </div>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
export default {
  name: 'XtxNumBox',
  props: {
    max: {
      type: Number
    },
    min: {
      type: Number
    },
    modelValue: {
      type: Number
    },
    isCount: {
      type: Boolean,
      default: true
    }
  },
  setup (props, ctx) {
    const count = ref(props.modelValue)

    // 子组件中监听这个modelValue参数属性
    watch(() => {
      return props.modelValue
    }, () => {
      // 如果父组件中的数据发生变化后，把发生变化后的数据，赋值给子组件中的数据
      count.value = props.modelValue
    })

    const ins = () => {
      if (count.value < props.max) {
        count.value++
      }
      // 触发emit事件
      ctx.emit('update:modelValue', count.value)
      // 触发自定义事件用来修改vuex数据的
      ctx.emit('change', count.value)
    }

    const desc = () => {
      if (count.value > props.min) {
        count.value--
      }
      ctx.emit('update:modelValue', count.value)
      // 触发自定义事件用来修改vuex数据的
      ctx.emit('change', count.value)
    }

    return {
      count,
      ins,
      desc
    }
  }
}
</script>
<style scoped lang="less">
.xtx-numbox {
  display: flex;
  align-items: center;
  .label {
    width: 60px;
    color: #999;
    padding-left: 10px;
  }
  .numbox {
    width: 120px;
    height: 30px;
    border: 1px solid #e4e4e4;
    display: flex;
    > a {
      width: 29px;
      line-height: 28px;
      text-align: center;
      background: #f8f8f8;
      font-size: 16px;
      color: #666;
      &:first-of-type {
        border-right: 1px solid #e4e4e4;
      }
      &:last-of-type {
        border-left: 1px solid #e4e4e4;
      }
    }
    > input {
      width: 60px;
      padding: 0 5px;
      text-align: center;
      color: #666;
    }
  }
}
</style>
